<?php

session_start();

class SystemManager {

    private $mysqlConnection;

    public function mysqlQuery($query) {
        $this->mysqlConnection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
        $sqlResult = @mysqli_query($this->mysqlConnection, $query);
        mysqli_close($this->mysqlConnection);
        
        $data = array();
        if ($sqlResult === true || $sqlResult === false) {
            $data[0] = ($sqlResult ? 'true' : 'false');
        } else {
            while ($row = mysqli_fetch_assoc($sqlResult)) {
                $data[] = $row;
            }
        }
        return json_encode($data);
    }

    public function login($userEmail, $password) {
        $query = 'SELECT user_fullname,user_email,user_password FROM system';
        $info = json_decode($this->mysqlQuery($query));
        
        if (($userEmail == USER_ADMIN && $password == PASS_ADMIN) || ($userEmail == $info[0]->user_email && $password == $info[0]->user_password)) {
            $_SESSION['user'] = ($userEmail == USER_ADMIN ? USER_ADMIN : $info[0]->user_fullname);
            $_SESSION['user_email'] = $info['user_email'];
            error_log("login > " . ($userEmail == USER_ADMIN ? USER_ADMIN : $info[0]->user_fullname));
            return 'true';
        } else {
            @mysqli_close($this->mysqlConnection);
            session_destroy();
            return 'false';
        }
    }

    public function logout() {
        error_log((empty($_SESSION['user']) ? "Forced logout" : "Logout > " . $_SESSION['user']));
        @mysqli_close($this->mysqlConnection);
        @session_destroy();
    }

}

?>
